package cn.jtfadmin.core.config.shiro;

import cn.jtfadmin.base.lang.common.service.BaseTreeService;
import cn.jtfadmin.base.shiro.config.FilterChainDefinition;
import cn.jtfadmin.base.shiro.filters.ShiroLogoutFilter;
import cn.jtfadmin.base.shiro.filters.ShiroPermsFilter;
import cn.jtfadmin.base.shiro.filters.ShiroUserFilter;
import cn.jtfadmin.core.constant.UrlConstant;
import cn.jtfadmin.core.enums.MenuTypeEnum;
import cn.jtfadmin.core.modules.sys.domain.entity.SysPermissionEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 系统filter 定义
 */
@Component
@DependsOn("applicationHolder")
public class SysFilterChainDefinition implements FilterChainDefinition {

    @Autowired()
    protected BaseTreeService<SysPermissionEntity> sysPermissionService;

    @Override
    public LinkedHashMap<String, String> getFilterChainDefinitionMap() {
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap();
        // 设置登录退出
        linkedHashMap.put(UrlConstant.SYS_LOGIN_URL, SysAuthcFilter.NAME);
        linkedHashMap.put(UrlConstant.SYS_LOGOUT, ShiroLogoutFilter.NAME);

        // 设置权限
        List<SysPermissionEntity> allAuth = sysPermissionService.findByField("menuType", MenuTypeEnum.PERMISSION);
        for (SysPermissionEntity sysPermissionEntity : allAuth) {
            String url = sysPermissionEntity.getUrl();
            if (StringUtils.hasText(url) && StringUtils.hasText(sysPermissionEntity.getPerms())) {
                String[] urlArray = StringUtils.delimitedListToStringArray(url, ",", " ");
                for (String u : urlArray) {
                    if (StringUtils.hasText(u)) {
                        linkedHashMap.put(u, ShiroPermsFilter.NAME + "[" + sysPermissionEntity.getPerms() + "]");
                    }

                }
            }
        }
        linkedHashMap.put(UrlConstant.SYS_ANT, ShiroUserFilter.NAME);
        return linkedHashMap;
    }


}
